package com.liaoxuefeng.java_thread.java01;

import javafx.beans.binding.StringBinding;

import java.util.StringJoiner;

public class StringBufferTest {

    public static void main(String[] args) {

        /*String s = "";
        for (int i = 0; i < 1000; i++) {
            s = s + "," + i;
        }
        System.out.println(s);*/

        StringBuilder sb = new StringBuilder(1024);
        for (int i = 0; i < 1000; i++) {
            sb.append(",");
            sb.append(i);
        }
        System.out.println(sb);

        // append 追加
        // insert 指定位置插入数据
        StringBuilder sb2 = new StringBuilder(1024);
        sb2.append("Mr")
                .append("Bob")
                .append("!")
                .insert(0, "Hello, ");
        System.out.println(sb2);

        String[] fields = {"name", "position", "salary"};
        String table = "employee";
        String insert = buildInsertSql(table, fields);
        System.out.println(insert);

        String sql = "INSERT INTO employee (name, position, salary) VALUES(?, ?, ?)";
        System.out.println(sql.equals(insert) ? "测试成功!": "测试失败!");

        StringJoiner fieldString = new StringJoiner(", ", "Hello ", " !");
        for(String name : fields) {
            fieldString.add(name);
        }
        System.out.println("使用分隔符拼接数组: "+ fieldString.toString());

        String selectSql = buildSelectSql(table, fields);
        System.out.println(selectSql);
    }

    static String buildInsertSql(String table, String[] fields) {

        StringBuilder sb = new StringBuilder(1024);
        sb.append("INSERT INTO ")
                .append(table)
                .append(" (");
        String values = " VALUES(";

        int size = fields.length;
        for (int i = 0; i < size; i++) {
            sb.append(fields[i]);
            if (i < (size - 1)) {
                sb.append(", ");
                values = values +  "?, ";
            } else {
                sb.append(")");
                values = values +  "?)";
            }
        }
        sb.append(values);
        return sb.toString();
    }

    static String buildSelectSql(String table, String[] fields) {
        StringJoiner sj = new StringJoiner(", ", "SELECT ", " FROM " + table);
        for (String name : fields) {
            sj.add(name);
        }
        return sj.toString();
    }
}
